<template>
  <el-dialog
    class="basic-dialog"
    :model-value="visible"
    :title="pageTitle"
    :width="576"
    :close-on-click-modal="!loading"
    :close-on-press-escape="!loading"
    :show-close="!loading"
    @closed="handleClosed"
    @open="handleDialogOpen"
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      class="w-full"
      label-width="92"
      label-position="left"
      require-asterisk-position="right"
    >
      <el-form-item label="账号" prop="username">
        <el-input
          v-model="formState.username"
          :disabled="!!props.record?.id"
          maxlength="18"
          show-word-limit
          placeholder="请输入账号"
        ></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-input
          v-model="formState.role"
          disabled
          placeholder="请输入角色"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="!record" label="密码" prop="password">
        <basic-password-input
          :key="passwordKey"
          v-model="formState.password"
          placeholder="请输入密码"
          default-type="text"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formState.remark"
          placeholder="请填写备注"
          maxlength="200"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <basic-switch
          v-model="formState.status"
          :disabled="record?.id === appStore.userInfo?.id"
        ></basic-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :loading="loading" type="primary" @click="handleSubmit">
        确定
      </el-button>
      <el-button :loading="loading" @click="emit('update:visible', false)"
        >取消</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { type FormInstance, type FormItemRule } from 'element-plus'

import type { AdminModel } from '@/apis/model/admin'
import type { UserModel } from '@/apis/model/user'
import { useAppStore } from '@/stores/modules/app'

interface IProps {
  visible: boolean
  record?: AdminModel | undefined | null
}

const appStore = useAppStore()

interface IEmits {
  // 更新 显示状态
  (event: 'update:visible', value: boolean): void
  // 更新 数据
  (event: 'update:record', value?: UserModel): void
  // 通知上层更新
  (event: 'reload'): void
}

const emit = defineEmits<IEmits>()
const props = withDefaults(defineProps<IProps>(), {})
const pageTitle = computed(() =>
  props.record?.id ? '编辑管理员' : '添加管理员'
)

const formRef = ref<FormInstance>()
const passwordKey = ref(Date.now())

const formState = ref({
  username: '',
  role: '管理员',
  remark: '',
  status: 1,
  password: DEFAULT_PASSWORD
})

const rules: Record<string, FormItemRule[]> = {
  username: [
    { required: true, trigger: 'blur', validator: accountValidate },
    { min: 2, max: 18, message: '账号长度为2-18', trigger: 'blur' }
  ],
  role: [{ required: true }],
  password: [
    { required: true, message: '请输入密码' },
    {
      trigger: 'blur',
      validator: passwordValidate
    }
  ]
}

const loading = ref(false)

/**
 * 保存方法
 */
const handleSubmit = async () => {
  await formRef.value?.validate()
  loading.value = true
  try {
    if (props.record?.id) {
      await putAdminApi({
        id: props.record.id as unknown as string,
        status: formState.value.status,
        remark: formState.value.remark
      })
    } else {
      await postAdminApi(formState.value)
    }

    emit('update:visible', false)
    emit('reload')
    ToastUtils.success(props?.record?.id ? '修改成功' : '创建成功')
  } finally {
    loading.value = false
  }
}

/**
 * @description dialog 打开事件
 */
const handleDialogOpen = () => {
  if (props.record?.id) {
    formState.value = {
      ...formState.value,
      username: props.record.username!,
      status: props.record.status!,
      remark: props.record.remark!
    }
  }
}

/**
 * @description dialog 关闭前事件
 */
const handleClosed = () => {
  emit('update:record', undefined)
  emit('update:visible', false)
  formRef.value?.resetFields()
  passwordKey.value = Date.now()
}
</script>

<style scoped></style>
